package cn.zifangsky.jvm.part2.reference;

import java.lang.ref.WeakReference;

/**
 * 软引用
 *
 * @author zifangsky
 * @date 2020/7/11
 * @since 1.0.0
 */
public class WeakRef {

    public static void main(String[] args) {
        User u = new User(1, "admin");
        WeakReference<User> userWeakRef = new WeakReference<>(u);
        //去除强引用
        u = null;

        System.out.println(userWeakRef.get());
        System.gc();
        //不管当前内存空间足够与否，都会回收它的内存
        System.out.println("第一次GC后：" + userWeakRef.get());
    }


    public static class User {
        private int id;
        private String name;
        private byte[] arr;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
            //默认申请一个占4M内存的数组
            this.arr = new byte[1024 * 1024 * 4];
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "[id=" + String.valueOf(id) + ", name=" + name + "]";
        }
    }
}
